# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

from protoc import ProtoCompiler

from google.protobuf.descriptor_pb2 import FileDescriptorProto
from google.protobuf.descriptor import MakeDescriptor
from google.protobuf.reflection import GeneratedProtocolMessageType
from google.protobuf.message import Message


class ProtoCTests(unittest.TestCase):
    def testEverything(self):
        # Set up the source tree, the error collector, and the importer.
        compiler = ProtoCompiler.create()
        compiler.map_path('', 'testdata')

        # Import the test proto file.  Verify that it's not the empty string.
        string_des = compiler.parse('test.proto')
        self.assertTrue(string_des)

        # Create a real file descriptor from it.
        file_des_pb = FileDescriptorProto()
        file_des_pb.MergeFromString(string_des)

        # Search the file descriptor for MyMessage, an expected message
        # descriptor.
        for message in file_des_pb.message_type:
            if message.name == 'MyMessage':
                my_message_des = MakeDescriptor(message)
                break
        else:
            self.fail('no descriptor for MyMessage')

        # Try creating a message class and a message from it.
        my_message_class = GeneratedProtocolMessageType('MyMessage', (Message,),
                                                        {'DESCRIPTOR': my_message_des})
        my_message = my_message_class()
        my_message.a = 100
        my_message.b = 'some data'
        self.assertEqual(str(my_message), 'a: 100\nb: "some data"\n')


if __name__ == '__main__':
    unittest.main()
